<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="1"
          placeholder="地址查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="loanBehStatusSelected"
          placeholder="项目状态选择"
          clearable
          number-key
          :options="{ 0: '在保项目', 1: '解保项目' }"
          @change="handleStatusChange"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-org-bank
          v-model="bankId"
          placeholder="选择银行"
          filterable
          clearable
          @select="selectBank"
        ></select-org-bank>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="放款开始日期"
          end-placeholder="放款结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumISNom"
          clearable
          v-model="params['is_9_3.eq']"
          @change="getData()"
          placeholder="9+3贫困县"
        ></c-select>
      </el-form-item>
      <!-- <el-form-item>
        <c-select :options="enumISNom"
                  clearable
                  v-model="params['is_refer_county.eq']"
                  @change="getData()"
                  placeholder="参考大县"></c-select>
      </el-form-item> -->
      <el-form-item>
        <c-select
          :options="enumISNom"
          clearable
          v-model="params['is_assess_county.eq']"
          @change="getData()"
          placeholder="农业大县"
        ></c-select>
      </el-form-item>
      <!-- <el-form-item>
        <c-select :options="enumISNom"
                  clearable
                  v-model="params['is_bus_assess_county.eq']"
                  @change="getData()"
                  placeholder="业务覆盖率考核大县"></c-select>
      </el-form-item> -->
      <el-form-item>
        <c-select
          v-model="fundsBetween"
          clearable
          :options="enumFundsItem"
          @change="setFundsParams"
          placeholder="放款金额区间"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="business"
          :options="enumParentBusiness"
          @change="setBusinessParams"
          clearable
          style="width: 320px"
          multiple
          placeholder="所属行业"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-popover v-model="selectVisible" placement="bottom" trigger="hover" width="400">
          <el-button type="primary" :loading="exportLoading" slot="reference">报表下载</el-button>
          <div>
            <div class="dl-wrap mb-1">
              <div class="dl-dt mt-1 text-right pr-2">选择担保年份</div>
              <div class="dl-dd">
                <el-date-picker
                  v-model="selectYear"
                  placeholder="选择年份"
                  :picker-options="pickerYear"
                  type="year"
                  value-format="yyyy"
                ></el-date-picker>
              </div>
            </div>
            <div class="dl-wrap mb-1">
              <div class="dl-dt"></div>
              <div class="dl-dd">
                <el-button
                  icon="el-icon-download"
                  type="primary"
                  :loading="exportLoading"
                  @click="exportExcel(innterTitle)"
                >
                  下载
                </el-button>
              </div>
            </div>
          </div>
        </el-popover>
      </el-form-item>
    </el-form>

    <!-- <h4 class="text-center font-weight-bold">{{innterTitle}}</h4> -->

    <c-table
      v-loading="loading"
      border
      header-row-class-name="mutiple-table-header"
      :columns="tableColumns"
      :data="tableData"
    >
      <template v-slot:warranty_method="scope">
        <div class="text-truncate" :title="scope.row.warranty_method">
          {{ scope.row.warranty_method }}
        </div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { lastPickerShortcuts, nextPickerShortcuts } from '@/common/plugins/tools/date'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
import {
  ledgerTwelveTableColumns,
  reportDataAdapter,
} from '@/credit/views/city/report/reportMixins'

import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'
import { enumISNom } from '@/gov/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
import { enumParentBusiness } from '@/bank/plugins/enum'
export default {
  components: {
    SelectOrgBank,
    SelectAddress,
  },
  props: {},
  data() {
    return {
      enumParentBusiness,
      enumISNom,
      loading: false,
      params: {
        index: 1,
        size: 10,
        load_beh_status: '',
        'orWhere.service_id.eq': '',
        'orWhere.pro_service.eq': '',
        'bank_id.eq': '',
      },
      order: { load_date: 'desc' },
      tableName: 'market_project',
      totalCount: 0,
      tableData: [],
      tableColumns: [...ledgerTwelveTableColumns],

      exportLoading: false,

      loanBehStatusSelected: '',
      datePicked: [],
      pickerOptions: {
        shortcuts: [...lastPickerShortcuts, ...nextPickerShortcuts],
      },
      selectVisible: false,
      selectYear: '',
      bankId: '',
      fundsBetween: '',
      enumFundsItem: {
        1: '小于10万元',
        2: '大于等于10万元并且小于等于300万元',
        3: '大于300万元',
      },
      business: '',
    }
  },
  computed: {
    ...mapGetters(['org', 'clientId']),
    innterTitle() {
      return `${this.org.orgName} “黔农十二贷”项目统计表-${this.selectYear}年`
    },
    pickerYear() {
      return {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      }
    },
  },
  watch: {},
  created() {
    this.params['orWhere.service_id.eq'] = this.clientId
    this.params['orWhere.pro_service.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    selectBank(bank) {
      this.params['bank_code.endlike'] = bank.agency_code
      this.getData()
    },
    setFundsParams(value) {
      this.params['warranty_amount.lt'] = ''
      this.params['warranty_amount.gte'] = ''
      this.params['warranty_amount.lte'] = ''
      this.params['warranty_amount.gt'] = ''
      switch (+value) {
        case 1:
          this.params['warranty_amount.lt'] = 10
          break
        case 2:
          this.params['warranty_amount.gte'] = 10
          this.params['warranty_amount.lte'] = 300
          break
        case 3:
          this.params['warranty_amount.gt'] = 300
          break
        default:
          break
      }
      this.getData()
    },
    setBusinessParams(value) {
      const business = []
      value.forEach(item => {
        business.push(enumParentBusiness[item])
      })
      this.params['parent_main_business.in'] = business.join(',')
      this.getData()
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.fetchData(this.params)
      this.loading = false
      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(reportDataAdapter)
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    handleDateChange() {
      this.params.index = 1
      if (this.datePicked && this.datePicked.length === 2) {
        this.params['load_date.gte'] = this.datePicked[0]
        this.params['load_date.lte'] = `${this.datePicked[1]} 23:59:59`
      } else {
        this.params['load_date.gte'] = ''
        this.params['load_date.lte'] = ''
      }
      this.getData()
    },
    handleStatusChange() {
      switch (this.loanBehStatusSelected) {
        case 0:
          this.params['load_beh_status.neq'] = 6
          this.params['load_beh_status.eq'] = ''
          break
        case 1:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = 6
          break
        default:
          this.params['load_beh_status.neq'] = ''
          this.params['load_beh_status.eq'] = ''
          break
      }
      this.getData()
    },
    async exportExcel(filename) {
      this.selectVisible = false
      let params = {}
      if (this.selectYear) {
        params = {
          'load_date.gte': `${this.selectYear}-01-01`,
          'load_date.lt': `${+this.selectYear + 1}-01-01`,
        }
      }
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: { ...this.params, ...params },
        dataAdapter: reportDataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除?`,
          beforeClose: () =>
            this.$api.deleteData(
              this.$serviceName,
              'datum_one_county_industry',
              row.customer_related_id
            ),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>

<style lang="scss" scoped></style>
